import { formatTime, getToday } from "../../utils/util.js";

// 引入API
const {
  appointmentConfigApi,
  appointmentApi,
  settingsApi,
} = require("../../utils/api.js");
Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    dateTime: null,
    selectedDate: null, // 选择的日期
    selectedTimeSlot: null, // 选择的时间段
    timeSlots: [], // 可用时间段列表
    name: "",
    phone: "",
    minDate: getToday(),
    fileList: [],
    userInfo: null,
    productTitle: "", // 预约商品标题
    serviceId: 1, // 服务ID
    phoneHidden: false,
    isLeave: false, // 是否请假
    leaveReason: "", // 请假原因
    workStartTime: "09:30", // 上班时间
    workEndTime: "22:00", // 下班时间
    userSettings: {
      setting2: "",
      setting3: "",
    },
    availableDates: [], // 可用的预约日期
    maxDate: null, // 最大可选日期
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 从URL参数中获取serviceId和productTitle
    let productTitle = "";
    if (options.serviceId) {
      this.setData({
        serviceId: parseInt(options.serviceId),
      });
    }
    if (options.productTitle) {
      productTitle = decodeURIComponent(options.productTitle);
      this.setData({
        productTitle: productTitle,
      });
    }

    // 如果 productTitle 为空但 serviceId 存在，尝试从服务器获取商品信息
    if ((!productTitle || productTitle.trim() === "") && options.serviceId) {
      this.loadProductTitle(parseInt(options.serviceId));
    }

    // 加载用户信息
    this.loadUserInfo();

    // 加载用户设置
    this.loadUserSettings();

    // 加载可用日期
    this.loadAvailableDates();
  },

  /**
   * 根据 serviceId 加载商品标题（兜底方案）
   */
  async loadProductTitle(serviceId) {
    try {
      const { productApi } = require("../../utils/api.js");
      const result = await productApi.getProduct(serviceId);

      if (result.code === 0 && result.data) {
        const productName = result.data.name || "";
        if (productName) {
          this.setData({
            productTitle: productName,
          });
          console.log(`[预约页面] 成功从服务器获取商品标题: ${productName}`);
        }
      }
    } catch (error) {
      console.error(
        `[预约页面] 获取商品标题失败 (serviceId=${serviceId}):`,
        error
      );
      // 失败时不影响主流程，继续使用空标题
    }
  },

  /**
   * 页面方法列表
   */
  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync("userInfo");
      if (userInfo) {
        // 检查用户是否被拉黑
        await this.checkUserBlacklist();

        this.setData({
          userInfo: userInfo,
          name: userInfo.nickname || "",
          phone: userInfo.phone || "",
        });
      } else {
        // 如果没有用户信息，显示空值
        this.setData({
          userInfo: null,
          name: "",
          phone: "",
        });
      }
    } catch (error) {
      console.error("加载用户信息失败:", error);
      this.setData({
        userInfo: null,
        name: "",
        phone: "",
      });
    }
  },

  /**
   * 加载用户设置
   */
  async loadUserSettings() {
    try {
      const result = await settingsApi.getUserSettings();
      if (result.code === 0 && result.data) {
        this.setData({
          phoneHidden: result.data.phone_hidden || false,
          userSettings: result.data,
        });
      }
    } catch (error) {
      console.error("加载用户设置失败:", error);
      this.setData({
        phoneHidden: false,
        userSettings: {
          setting2: "",
          setting3: "",
        },
      });
    }
  },

  /**
   * 检查用户是否被拉黑
   */
  async checkUserBlacklist() {
    try {
      const { userApi } = require("../../utils/api.js");
      const result = await userApi.checkUserBlacklist();

      if (result.code === 0 && result.data && result.data.is_blacklisted) {
        wx.showModal({
          title: "网络异常",
          content: "网络异常，请稍后再试。",
          showCancel: false,
          confirmText: "确定",
          success: () => {
            wx.navigateBack();
          },
        });
        return true; // 返回true表示被拉黑
      }
      return false; // 返回false表示未被拉黑
    } catch (error) {
      console.error("检查用户拉黑状态失败:", error);
      return false; // 出错时默认允许预约
    }
  },

  /**
   * 检查用户是否已注册
   */
  checkUserRegistration() {
    const userInfo = wx.getStorageSync("userInfo");
    if (!userInfo) {
      wx.showModal({
        title: "需要注册",
        content: "请先注册用户信息才能进行预约",
        showCancel: true,
        cancelText: "取消",
        confirmText: "去注册",
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: "/pages/register/index",
            });
          }
        },
      });
      return false;
    }
    return true;
  },

  /**
   * 检查用户登录状态
   */
  checkUserLogin() {
    const userInfo = wx.getStorageSync("userInfo");
    const token = wx.getStorageSync("token");

    if (!userInfo || !token) {
      wx.showModal({
        title: "需要登录",
        content: "请先登录才能进行预约",
        showCancel: true,
        cancelText: "取消",
        confirmText: "去登录",
        success: (res) => {
          if (res.confirm) {
            // 跳转到登录页面，并传递当前页面的参数以便登录后返回
            const { serviceId, productTitle } = this.data;
            const returnUrl = `/pages/appointment/appointment?serviceId=${serviceId}&productTitle=${encodeURIComponent(
              productTitle
            )}`;
            wx.navigateTo({
              url: `/pages/login/index?returnUrl=${encodeURIComponent(
                returnUrl
              )}`,
            });
          }
        },
      });
      return false;
    }
    return true;
  },

  /**
   * 检查日期可用性并计算时间段
   */
  async checkDateAvailability(date) {
    try {
      wx.showLoading({
        title: "检查日期...",
      });

      // 获取该日期的预约配置
      const result = await appointmentConfigApi.getAppointmentConfig(date);

      if (result.code === 0 && result.data) {
        const config = result.data;

        // 检查是否请假
        if (config.is_leave) {
          wx.hideLoading();
          wx.showToast({
            title: "该日期已休息，请选择其他日期",
            icon: "none",
            duration: 3000,
          });

          this.setData({
            isLeave: true,
            leaveReason: config.leave_reason || "",
            timeSlots: [],
            selectedTimeSlot: null,
          });
          return false;
        }

        // 如果未请假，计算可用时间段
        this.setData({
          isLeave: false,
          leaveReason: "",
          workStartTime: config.start_time || "09:30",
          workEndTime: config.end_time || "22:00",
        });

        // 计算时间段
        this.calculateTimeSlots(
          config.start_time || "09:30",
          config.end_time || "22:00",
          date
        );
      } else {
        // 如果没有配置，使用默认时间
        this.setData({
          isLeave: false,
          leaveReason: "",
          workStartTime: "09:30",
          workEndTime: "22:00",
        });
        this.calculateTimeSlots("09:30", "22:00", date);
      }

      // 检查已预约的时间段
      await this.checkBookedTimeSlots(date);

      wx.hideLoading();
      return true;
    } catch (error) {
      wx.hideLoading();
      console.error("检查日期可用性失败:", error);

      // 出错时使用默认时间
      this.setData({
        isLeave: false,
        leaveReason: "",
        workStartTime: "09:30",
        workEndTime: "22:00",
      });
      this.calculateTimeSlots("09:30", "22:00", date);
      return true;
    }
  },

  /**
   * 计算可用时间段（每2小时一个时段）
   * @param {string} startTime - 开始时间，格式 "HH:mm"
   * @param {string} endTime - 结束时间，格式 "HH:mm"
   * @param {string} date - 选择的日期，格式 "YYYY-MM-DD"
   */
  calculateTimeSlots(startTime, endTime, date) {
    const slots = [];
    const startHour = parseInt(startTime.split(":")[0]);
    const startMinute = parseInt(startTime.split(":")[1]);
    const endHour = parseInt(endTime.split(":")[0]);
    const endMinute = parseInt(endTime.split(":")[1]);

    // 将时间转换为分钟数
    const startMinutes = startHour * 60 + startMinute;
    const endMinutes = endHour * 60 + endMinute;
    const slotDuration = 120; // 2小时 = 120分钟

    // 判断是否是今天
    const isToday = this.isToday(date);
    let currentTimeMinutes = null;
    if (isToday) {
      // 如果是今天，获取当前时间（分钟数）
      const now = new Date();
      currentTimeMinutes = now.getHours() * 60 + now.getMinutes();
    }

    let slotNumber = 1;
    let currentTime = startMinutes;

    while (currentTime + slotDuration <= endMinutes) {
      const slotStartHour = Math.floor(currentTime / 60);
      const slotStartMinute = currentTime % 60;
      const slotEndTime = currentTime + slotDuration;
      const slotEndHour = Math.floor(slotEndTime / 60);
      const slotEndMinute = slotEndTime % 60;

      // 格式化时间
      const formatTime = (hour, minute) => {
        return `${hour.toString().padStart(2, "0")}:${minute
          .toString()
          .padStart(2, "0")}`;
      };

      const slotStartTimeStr = formatTime(slotStartHour, slotStartMinute);
      const slotEndTimeStr = formatTime(slotEndHour, slotEndMinute);

      // 判断是否是今天，且时间段开始时间已经过去
      const isExpired =
        isToday &&
        currentTimeMinutes !== null &&
        currentTime <= currentTimeMinutes;

      // 只添加未过期的时间段，但编号要保持连续（不管是否过期都要递增）
      if (!isExpired) {
        slots.push({
          number: slotNumber,
          startTime: slotStartTimeStr,
          endTime: slotEndTimeStr,
          displayText: `${slotNumber}号：预计${slotStartTimeStr}到店`,
          value: `${slotStartTimeStr}-${slotEndTimeStr}`,
        });
      }

      currentTime += slotDuration;
      slotNumber++; // 编号始终递增，保持原始顺序，即使时间段被过滤掉
    }

    this.setData({
      timeSlots: slots,
    });
  },

  /**
   * 判断选择的日期是否是今天
   * @param {string} date - 日期字符串，格式 "YYYY-MM-DD"
   * @returns {boolean}
   */
  isToday(date) {
    if (!date) return false;
    const today = new Date();
    const todayStr = `${today.getFullYear()}-${String(
      today.getMonth() + 1
    ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
    return date === todayStr;
  },

  /**
   * 检查已预约的时间段
   */
  async checkBookedTimeSlots(date) {
    try {
      const result = await appointmentConfigApi.getBookedTimeSlots(date);

      if (result.code === 0 && result.data) {
        const bookedCounts = result.data.booked_counts || {}; // queue_number -> 已预约数量
        const staffCount = result.data.staff_count || 1; // 美甲师人数

        // 更新时间段状态
        const updatedTimeSlots = this.data.timeSlots.map((slot) => {
          const bookedCount = bookedCounts[slot.number] || 0; // 该时间段已预约数量
          const isFull = bookedCount >= staffCount; // 是否已满

          return {
            ...slot,
            bookedCount: bookedCount, // 已预约数量
            staffCount: staffCount, // 美甲师人数
            isBooked: isFull, // 是否已满（用于兼容旧逻辑）
            disabled: isFull, // 是否禁用
            displayText: `${slot.number}号：预计${slot.startTime}到店 (${bookedCount}/${staffCount})`, // 显示已预约数量/美甲师人数
          };
        });

        this.setData({
          timeSlots: updatedTimeSlots,
        });
      }
    } catch (error) {
      console.error("检查已预约时间段失败:", error);
      // 出错时不影响主流程，继续显示所有时间段
    }
  },
  async afterRead(event) {
    const { file, fileList } = event.detail;

    // 检查file是否存在
    if (!file) {
      wx.showToast({
        title: "文件信息获取失败",
        icon: "none",
      });
      return;
    }

    // 处理多文件上传，file可能是数组
    const files = Array.isArray(file) ? file : [file];

    // 显示上传中状态
    const { fileList: currentFileList = [] } = this.data;

    // 为每个文件添加唯一标识和上传中状态
    const fileUploadTasks = files.map((fileItem, index) => {
      const uniqueId = `upload_${Date.now()}_${index}_${Math.random()
        .toString(36)
        .substr(2, 9)}`;
      const newFile = {
        ...fileItem,
        uploadId: uniqueId, // 添加唯一标识
        status: "uploading",
        message: "上传中...",
      };
      currentFileList.push(newFile);
      return {
        fileItem,
        uploadId: uniqueId,
        index: currentFileList.length - 1, // 记录在列表中的索引
      };
    });

    this.setData({ fileList: currentFileList });

    // 逐个上传文件
    for (let i = 0; i < fileUploadTasks.length; i++) {
      const { fileItem, uploadId } = fileUploadTasks[i];
      try {
        // 实际上传图片到服务器
        const { productApi } = require("../../utils/api.js");

        // 使用正确的文件路径
        let filePath = fileItem.tempFilePath || fileItem.path || fileItem.url;

        // 检查文件大小并压缩
        const fileInfo = await new Promise((resolve) => {
          wx.getFileInfo({
            filePath: filePath,
            success: (res) => {
              resolve(res);
            },
            fail: (error) => {
              resolve({ size: 0 });
            },
          });
        });

        const fileSizeKB = fileInfo.size / 1024;

        // 如果文件超过1.5MB，进行压缩
        if (fileSizeKB > 1500) {
          filePath = await new Promise((resolve) => {
            wx.compressImage({
              src: filePath,
              quality: 0.3, // 降低压缩质量
              success: (res) => {
                // 检查压缩后的文件大小
                wx.getFileInfo({
                  filePath: res.tempFilePath,
                  success: (compressedInfo) => {
                    const compressedSizeKB = compressedInfo.size / 1024;
                    resolve(res.tempFilePath);
                  },
                  fail: () => resolve(res.tempFilePath),
                });
              },
              fail: () => resolve(filePath),
            });
          });
        }

        // 最终检查文件大小，确保不超过2MB
        const finalFileInfo = await new Promise((resolve) => {
          wx.getFileInfo({
            filePath: filePath,
            success: resolve,
            fail: () => resolve({ size: 0 }),
          });
        });

        const finalSizeKB = finalFileInfo.size / 1024;

        if (finalSizeKB > 2000) {
          throw new Error(
            `文件过大 (${finalSizeKB.toFixed(2)}KB)，请选择更小的图片`
          );
        }

        const result = await productApi.uploadImage(filePath);

        if (result.code === 0) {
          // 上传成功，根据唯一标识更新对应文件的状态
          const currentList = this.data.fileList || [];
          const updatedFileList = currentList.map((item) => {
            if (item.uploadId === uploadId) {
              return {
                ...item,
                url: result.data.url, // 使用服务器返回的URL
                status: "done",
                message: "上传成功",
              };
            }
            return item;
          });

          this.setData({ fileList: updatedFileList });
        } else {
          throw new Error(result.message || "上传失败");
        }
      } catch (error) {
        // 上传失败，根据唯一标识更新对应文件的状态
        const currentList = this.data.fileList || [];
        const updatedFileList = currentList.map((item) => {
          if (item.uploadId === uploadId) {
            return {
              ...item,
              status: "failed",
              message: error.message || "上传失败",
            };
          }
          return item;
        });

        this.setData({ fileList: updatedFileList });

        // 显示具体的错误信息
        wx.showToast({
          title: `第${i + 1}张图片上传失败: ${error.message || "未知错误"}`,
          icon: "none",
          duration: 3000,
        });
      }
    }

    // 检查是否所有文件都上传完成
    const finalFileList = this.data.fileList;
    const successCount = finalFileList.filter(
      (item) => item.status === "done"
    ).length;
    const failCount = finalFileList.filter(
      (item) => item.status === "failed"
    ).length;

    if (successCount > 0) {
      wx.showToast({
        title: `成功上传${successCount}张图片`,
        icon: "success",
        duration: 1500,
      });
    }

    if (failCount > 0) {
      wx.showToast({
        title: `${failCount}张图片上传失败`,
        icon: "none",
        duration: 2000,
      });
    }
  },

  // 删除图片
  deleteImage(event) {
    const { index } = event.detail;
    const { fileList = [] } = this.data;
    fileList.splice(index, 1);
    this.setData({ fileList });

    wx.showToast({
      title: "图片已删除",
      icon: "success",
      duration: 1000,
    });
  },

  // 预览图片
  previewImage(event) {
    const { index } = event.detail;
    const { fileList = [] } = this.data;

    if (fileList.length === 0) {
      wx.showToast({
        title: "没有可预览的图片",
        icon: "none",
      });
      return;
    }

    if (index === undefined || index < 0 || index >= fileList.length) {
      wx.showToast({
        title: "图片索引错误",
        icon: "none",
      });
      return;
    }

    const urls = fileList.map((file) => file.url).filter((url) => url);

    if (urls.length > 0 && urls[index]) {
      wx.previewImage({
        urls: urls,
        current: urls[index],
        success: () => {},
        fail: (err) => {
          wx.showToast({
            title: "图片预览失败",
            icon: "none",
          });
        },
      });
    } else {
      wx.showToast({
        title: "图片路径无效",
        icon: "none",
      });
    }
  },
  goBack() {
    wx.navigateBack({
      delta: 1,
    });
    this.setData({
      show: false,
      dateTime: null,
      selectedDate: null,
      selectedTimeSlot: null,
      timeSlots: [],
      name: "",
      isLeave: false,
      leaveReason: "",
    });
  },
  selectDate() {
    this.setData({
      dateTime: null,
      selectedDate: null,
      selectedTimeSlot: null,
      timeSlots: [],
      isLeave: false,
      leaveReason: "",
      show: true,
    });
  },
  onClose() {
    this.setData({
      dateTime: null,
      selectedDate: null,
      selectedTimeSlot: null,
      timeSlots: [],
      isLeave: false,
      leaveReason: "",
      show: false,
    });
  },
  async onConfirm(event) {
    const value = event.detail;

    // 处理不同的日期格式
    let dateTime, selectedDate;

    if (typeof value === "object" && value.value) {
      // 如果是对象格式 {value: Date}
      const date = new Date(value.value);
      dateTime = formatTime(date);
      selectedDate = this.formatDateForAPI(date);
    } else if (typeof value === "string") {
      // 如果是字符串格式
      dateTime = formatTime(value);
      selectedDate = value.split(" ")[0].replace(/\//g, "-");
    } else if (value instanceof Date) {
      // 如果是Date对象
      dateTime = formatTime(value);
      selectedDate = this.formatDateForAPI(value);
    } else {
      console.error("未知的日期格式:", value);
      wx.showToast({
        title: "日期格式错误",
        icon: "none",
      });
      return;
    }

    // 检查选择的日期是否可用
    if (!this.isDateAvailable(selectedDate)) {
      wx.showToast({
        title: "该日期不可预约，请选择其他日期",
        icon: "none",
      });
      return;
    }

    this.setData({
      dateTime: dateTime,
      selectedDate: selectedDate,
      show: false,
      selectedTimeSlot: null, // 重置时间段选择
      timeSlots: [], // 重置时间段列表
    });

    // 检查该日期的预约配置和已预约时间段
    await this.checkDateAvailability(selectedDate);
  },

  // 格式化日期为API需要的格式 (YYYY-MM-DD)
  formatDateForAPI(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  },

  // 处理姓名输入
  onNameChange(event) {
    const name = event.detail;
    this.setData({
      name: name,
    });
  },

  onPhoneChange(event) {
    const phone = event.detail;
    this.setData({
      phone: phone,
    });
  },

  // 选择时间段
  async selectTimeSlot(event) {
    const { slot } = event.currentTarget.dataset;

    // 检查时间段是否已被预约
    if (slot.disabled || slot.isBooked) {
      wx.showToast({
        title: "该时间段已被预约",
        icon: "none",
        duration: 2000,
      });
      return;
    }

    this.setData({
      selectedTimeSlot: slot,
    });

    // 选择时间段后立即提示订阅消息
    await this.checkAndRequestSubscribeMessage();
  },

  async save() {
    // 首先检查用户登录状态
    if (!this.checkUserLogin()) {
      return;
    }

    // 检查用户是否被拉黑
    const isBlacklisted = await this.checkUserBlacklist();
    if (isBlacklisted) {
      return; // 如果被拉黑，直接返回，不继续执行
    }

    // 在提交预约前，检查并请求订阅消息
    // 注意：必须在用户点击提交按钮时调用，不能自动调用
    
    // 检查第一个模板（取消预约通知）
    const hasCancelMessage = wx.getStorageSync("hasSubscribedCancelMessage");
    if (!hasCancelMessage) {
      await this.requestSubscribeMessage();
    }
    
    // 检查第二个模板（新预约通知）
    const hasNewAppointmentMessage = wx.getStorageSync("hasSubscribedNewAppointmentMessage");
    if (!hasNewAppointmentMessage) {
      await this.requestNewAppointmentMessage();
    }
    
    // 如果两个模板都已授权，设置完整授权标志
    const hasCancel = wx.getStorageSync("hasSubscribedCancelMessage");
    const hasNew = wx.getStorageSync("hasSubscribedNewAppointmentMessage");
    if (hasCancel && hasNew) {
      wx.setStorageSync("hasSubscribedMessage", true);
    }

    try {
      const {
        dateTime,
        name,
        phone,
        fileList,
        selectedDate,
        selectedTimeSlot,
        isLeave,
      } = this.data;

      // 检查是否选择了日期
      if (!dateTime || !selectedDate) {
        wx.showToast({
          title: "请选择预约日期",
          icon: "error",
        });
        return;
      }

      // 检查是否请假
      if (isLeave) {
        wx.showToast({
          title: "该日期已休息，请选择其他日期",
          icon: "none",
        });
        return;
      }

      // 检查是否选择了时间段
      if (!selectedTimeSlot) {
        wx.showToast({
          title: "请选择预约时间段",
          icon: "error",
        });
        return;
      }

      // 检查时间段是否已满（双重保险）
      if (selectedTimeSlot.disabled || selectedTimeSlot.isBooked) {
        wx.showToast({
          title: "该时间段已约满，请选择其他时间段",
          icon: "none",
          duration: 2000,
        });
        // 重新检查该日期的预约状态
        await this.checkDateAvailability(selectedDate);
        return;
      }

      // 检查时间段是否达到美甲师数量限制
      const bookedCount = selectedTimeSlot.bookedCount || 0;
      const staffCount = selectedTimeSlot.staffCount || 1;
      if (bookedCount >= staffCount) {
        wx.showToast({
          title: `该时间段已约满（${bookedCount}/${staffCount}），请选择其他时间段`,
          icon: "none",
          duration: 2000,
        });
        // 重新检查该日期的预约状态
        await this.checkDateAvailability(selectedDate);
        return;
      }

      // 表单验证
      if (!this.validateForm()) {
        return;
      }

      // 验证预约项目信息
      if (!this.data.productTitle || this.data.productTitle.trim() === "") {
        // 如果仍然没有商品标题，尝试再次从服务器获取
        if (this.data.serviceId) {
          try {
            await this.loadProductTitle(this.data.serviceId);
            // 重新获取后再次检查
            if (
              !this.data.productTitle ||
              this.data.productTitle.trim() === ""
            ) {
              wx.showToast({
                title: "无法获取预约项目信息，请返回重试",
                icon: "error",
                duration: 3000,
              });
              return;
            }
          } catch (error) {
            wx.showToast({
              title: "无法获取预约项目信息，请返回重试",
              icon: "error",
              duration: 3000,
            });
            return;
          }
        } else {
          wx.showToast({
            title: "缺少预约项目信息，请返回重试",
            icon: "error",
            duration: 3000,
          });
          return;
        }
      }

      wx.showLoading({
        title: "提交中...",
      });

      // 检查效果图上传状态
      const successImages = fileList.filter((file) => file.status === "done");
      const failedImages = fileList.filter((file) => file.status === "failed");

      let remarkText = `预约时间段：${selectedTimeSlot.displayText}`;
      if (successImages.length > 0) {
        remarkText += `，已上传${successImages.length}张效果图`;
      }
      if (failedImages.length > 0) {
        remarkText += `，${failedImages.length}张上传失败`;
      }

      // 构建预约数据，包含用户选择的排号和预计时间
      const appointmentData = {
        date: selectedDate, // 使用选择的日期
        appointment_time: selectedTimeSlot.startTime, // 使用选择的时间段开始时间
        customer_name: name,
        customer_remark: remarkText,
        service_id: this.data.serviceId, // 服务ID
        product_title: this.data.productTitle, // 预约商品标题
        effect_images: successImages.map((file) => file.url), // 传递成功上传的效果图URLs
        // 新增字段：用户选择的排号和预计时间
        queue_number: selectedTimeSlot.number, // 用户选择的排号
        estimated_time: `${selectedDate} ${selectedTimeSlot.startTime}:00`, // 预计到店时间
      };

      if (!this.data.phoneHidden) {
        appointmentData.customer_phone = phone;
      }

      // 发送预约数据到服务器

      let appointmentResult;
      try {
        appointmentResult = await appointmentApi.createAppointment(
          appointmentData
        );
      } catch (appointmentError) {
        throw appointmentError;
      }

      // 从服务器响应中提取实际数据
      const serverResponse = appointmentResult.data || appointmentResult;

      // 保存到本地存储，使用服务器返回的数据
      this.saveAppointmentToLocal({
        id: serverResponse.id, // 使用服务器返回的ID
        appointment_date: serverResponse.appointment_date,
        appointment_time: serverResponse.appointment_time,
        status: serverResponse.status,
        customer_name: serverResponse.customer_name,
        customer_phone: serverResponse.customer_phone,
        customer_remark: serverResponse.customer_remark,
        effect_images: serverResponse.effect_images,
        queue_number: serverResponse.queue_number, // 使用服务器返回的排队号码
        estimated_time: serverResponse.estimated_time, // 使用服务器返回的预计到店时间
        created_at: new Date().toISOString(),
      });

      wx.hideLoading();

      // 显示成功提示，使用服务器返回的数据
      wx.showModal({
        title: "预约成功！",
        content: `您的预约已提交成功\n排队号码：${
          serverResponse.queue_number
        }\n预计到店时间：${this.formatEstimatedTime(
          serverResponse.estimated_time
        )}`,
        showCancel: false,
        confirmText: "知道了",
        success: (res) => {
          if (res.confirm) {
            // 点击"知道了"后强制跳转到首页
            wx.switchTab({
              url: "/pages/home/index",
            });
          }
        },
      });
    } catch (error) {
      wx.hideLoading();

      // 显示更详细的错误信息
      let errorMessage = "保存失败";
      if (error.statusCode === 400) {
        errorMessage = error.data.message;
      } else if (error.errMsg) {
        errorMessage = error.errMsg;
      }

      wx.showModal({
        title: "预约失败",
        content: `${errorMessage}`,
        showCancel: true,
        cancelText: "取消",
        confirmText: "重试",
        success: (res) => {
          if (res.confirm) {
            // 用户选择重试，重新提交
            this.save();
          }
        },
      });
    }
  },

  // 格式化预计时间显示
  formatEstimatedTime(estimatedTime) {
    try {
      // 直接解析服务器返回的时间字符串，避免时区转换问题
      // 服务器返回格式: "2025-09-29T10:30:00Z"
      const date = new Date(estimatedTime);

      // 使用UTC时间避免时区问题
      const year = date.getUTCFullYear();
      const month = String(date.getUTCMonth() + 1).padStart(2, "0");
      const day = String(date.getUTCDate()).padStart(2, "0");
      const hours = String(date.getUTCHours()).padStart(2, "0");
      const minutes = String(date.getUTCMinutes()).padStart(2, "0");

      // 检查是否是第二天（使用UTC时间比较）
      const today = new Date();
      const isNextDay =
        date.getUTCDate() !== today.getUTCDate() ||
        date.getUTCMonth() !== today.getUTCMonth() ||
        date.getUTCFullYear() !== today.getUTCFullYear();

      const dayText = isNextDay ? " (次日)" : "";
      return `${year}-${month}-${day} ${hours}:${minutes}${dayText}`;
    } catch (error) {
      console.error("格式化时间失败:", error);
      return "时间计算中...";
    }
  },

  // 保存预约到本地存储
  saveAppointmentToLocal(appointmentData) {
    try {
      // 获取现有的预约数据
      const existingAppointments = wx.getStorageSync("appointments") || [];

      // 添加新的预约
      existingAppointments.push(appointmentData);

      // 保存到本地存储
      wx.setStorageSync("appointments", existingAppointments);
    } catch (error) {
      // 保存预约到本地存储失败
    }
  },

  /**
   * 表单验证
   */
  validateForm() {
    const {
      dateTime,
      name,
      phone,
      fileList,
      phoneHidden,
      selectedTimeSlot,
      isLeave,
    } = this.data;

    // 验证预约时间
    if (!dateTime) {
      wx.showToast({
        title: "请选择预约日期",
        icon: "none",
      });
      return false;
    }

    // 验证是否请假
    if (isLeave) {
      wx.showToast({
        title: "该日期已休息，请选择其他日期",
        icon: "none",
      });
      return false;
    }

    // 验证时间段选择
    if (!selectedTimeSlot) {
      wx.showToast({
        title: "请选择预约时间段",
        icon: "none",
      });
      return false;
    }

    // 验证姓名
    if (!name || name.trim() === "") {
      wx.showToast({
        title: `请输入${this.data.userSettings.setting3}`,
        icon: "none",
      });
      return false;
    }

    if (!phoneHidden) {
      if (!phone || phone.trim() === "") {
        wx.showToast({
          title: `请输入${this.data.userSettings.setting2}`,
          icon: "none",
        });
        return false;
      }

      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(phone)) {
        wx.showToast({
          title: `请输入正确的${this.data.userSettings.setting2}`,
          icon: "none",
        });
        return false;
      }
    }

    // 效果图上传改为非必填，用户可以选择性上传
    // 注释掉必填验证，允许用户不上传效果图也能提交预约

    return true;
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: "甲年华美甲美睫 - 立即预约",
      desc: "专业美甲美睫服务，立即预约享受精致服务",
      path: "/pages/home/index",
      imageUrl: "/images/share-appointment.jpg",
    };
  },

  /**
   * 分享到朋友圈
   */
  onShareTimeline() {
    return {
      title: "甲年华美甲美睫 - 立即预约",
      query: "",
      imageUrl: "/images/share-appointment.jpg",
    };
  },

  /**
   * 加载可用日期
   */
  async loadAvailableDates() {
    try {
      const result = await appointmentConfigApi.getAvailableDates();
      if (result.code === 0 && result.data && result.data.dates) {
        const dates = result.data.dates;
        this.setData({
          availableDates: dates,
        });

        // 设置最大可选日期为表中存在的最大日期
        if (dates.length > 0) {
          // 找到最大日期（按日期对象比较，不是字符串比较）
          const maxDateStr = dates.reduce((max, current) => {
            const maxDate = new Date(max);
            const currentDate = new Date(current);
            return currentDate > maxDate ? current : max;
          });
          const maxDate = new Date(maxDateStr).getTime();
          this.setData({
            maxDate: maxDate,
            dateFormatter: this.createDateFormatter(dates),
          });
        }
      } else {
        console.error("获取可用日期失败:", result);
      }
    } catch (error) {
      console.error("加载可用日期失败:", error);
    }
  },

  /**
   * 检查日期是否可用
   */
  isDateAvailable(date) {
    const dateStr = this.formatDateForFormatter(date);
    return this.data.availableDates.includes(dateStr);
  },

  /**
   * 创建日期格式化器
   */
  createDateFormatter(availableDates) {
    return (day) => {
      const dateStr = this.formatDateForFormatter(day.date);
      const isAvailable = availableDates.includes(dateStr);

      // 只设置不可用日期的类型，保持其他属性不变
      if (!isAvailable) {
        day.type = "disabled";
      }
      // 注意：不设置 day.type = "normal"，让 Vant 保持默认样式

      return day;
    };
  },

  /**
   * 格式化日期为 YYYY-MM-DD 格式
   */
  formatDateOnly(date) {
    if (!date) return "";

    let d;
    if (typeof date === "number") {
      // 如果是时间戳
      d = new Date(date);
    } else if (typeof date === "string") {
      // 如果是字符串
      d = new Date(date);
    } else if (date instanceof Date) {
      // 如果是Date对象
      d = date;
    } else {
      // 其他情况，尝试直接转换
      d = new Date(date);
    }

    // 使用本地时间，避免时区问题
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    const result = `${year}-${month}-${day}`;

    return result;
  },

  /**
   * 格式化日期为 YYYY-MM-DD 格式（专门用于日期格式化器）
   */
  formatDateForFormatter(date) {
    if (!date) return "";

    let d;
    if (typeof date === "number") {
      // 如果是时间戳
      d = new Date(date);
    } else if (typeof date === "string") {
      // 如果是字符串
      d = new Date(date);
    } else if (date instanceof Date) {
      // 如果是Date对象
      d = date;
    } else {
      // 其他情况，尝试直接转换
      d = new Date(date);
    }

    // 使用本地时间
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  },

  /**
   * 检查并请求订阅消息（第一个模板：取消预约通知）
   */
  async checkAndRequestSubscribeMessage() {
    // 检查用户是否已经订阅过第一个模板
    const hasCancelMessage = wx.getStorageSync("hasSubscribedCancelMessage");
    const hasSubscribed = wx.getStorageSync("hasSubscribedMessage");

    if (!hasSubscribed && !hasCancelMessage) {
      // 如果用户从未订阅过，则请求第一个模板（取消预约通知）
      await this.requestSubscribeMessage();
    }
    // 如果用户已经订阅过，则跳过订阅请求
  },

  /**
   * 清除订阅状态（用于测试或重置）
   */
  clearSubscribeStatus() {
    wx.removeStorageSync("hasSubscribedMessage");
    wx.removeStorageSync("hasSubscribedCancelMessage");
    wx.removeStorageSync("hasSubscribedNewAppointmentMessage");
    console.log("已清除订阅状态");
    wx.showToast({
      title: "已清除订阅状态",
      icon: "success",
    });
  },

  /**
   * 请求订阅消息（取消预约通知）
   * 注意：必须由用户点击触发，不能自动调用
   */
  requestSubscribeMessage() {
    return new Promise((resolve) => {
      const templateId = "o7WljBjHOvNPXVvRdRO9pHFIOLO_pgbz3oc-WI4lng0";
      const templateName = "取消预约通知";

      wx.requestSubscribeMessage({
        tmplIds: [templateId],
        success: (res) => {
          console.log(`${templateName} 授权结果:`, res);
          const status = res[templateId] || "undefined";
          
          if (status === "accept") {
            wx.setStorageSync("hasSubscribedCancelMessage", true);
            wx.showToast({
              title: "取消预约通知已授权",
              icon: "success",
            });
          }
          
          resolve({ [templateId]: status });
        },
        fail: (err) => {
          console.error(`${templateName} 授权失败:`, err);
          resolve({ [templateId]: "fail" });
        },
      });
    });
  },

  /**
   * 请求订阅消息（新预约通知）
   * 注意：必须由用户点击触发，不能自动调用
   */
  requestNewAppointmentMessage() {
    return new Promise((resolve) => {
      const templateId = "ktex3oGhX7Bp8heWLu5dM10pRwXvtrQHEIkHNcNVGAQ";
      const templateName = "新预约通知";

      wx.requestSubscribeMessage({
        tmplIds: [templateId],
        success: (res) => {
          console.log(`${templateName} 授权结果:`, res);
          const status = res[templateId] || "undefined";
          
          if (status === "accept") {
            wx.setStorageSync("hasSubscribedNewAppointmentMessage", true);
            
            // 检查两个模板是否都已授权
            const hasCancelMessage = wx.getStorageSync("hasSubscribedCancelMessage");
            if (hasCancelMessage) {
              wx.setStorageSync("hasSubscribedMessage", true);
              wx.showToast({
                title: "已开启所有消息通知",
                icon: "success",
              });
            } else {
              wx.showToast({
                title: "新预约通知已授权",
                icon: "success",
              });
            }
          }
          
          resolve({ [templateId]: status });
        },
        fail: (err) => {
          console.error(`${templateName} 授权失败:`, err);
          resolve({ [templateId]: "fail" });
        },
      });
    });
  },
});
